﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using COFE.Core.Utils;
using COFE.Core.Lister;

namespace COFE.IO.COFEWS
{
    public class COFEWSFactory : IFactory<IDirectoryLister>
    {
        public COFEWSFactory(string factoryKey)
        {            
            FactoryKey = factoryKey;
        }

        public string FactoryKey { get; private set; }

        public IDirectoryLister Construct(string id, string paramString)
        {
            var paramDic = StringUtils.ParamStringToDic(paramString);

            if (paramDic.ContainsKey("rootUri") &&
                paramDic.ContainsKey("username") &&
                paramDic.ContainsKey("password"))
            {
                return new COFEWSDirectoryLister(this, id, 
                    paramDic["rootUri"],
                    paramDic["username"],
                    paramDic["password"]);
            }

            if (paramDic.ContainsKey("host") &&
                paramDic.ContainsKey("path") &&
                paramDic.ContainsKey("username") &&
                paramDic.ContainsKey("password"))
            {
                return new COFEWSDirectoryLister(this, id,
                    paramDic["host"],
                    paramDic["path"],
                    paramDic["username"],
                    paramDic["password"]);
            }

            else
                throw new ArgumentException();                            
        }

        public string Recycle(IDirectoryLister product)
        {
            COFEWSDirectoryLister lister = (COFEWSDirectoryLister)product;

            Func<string, string> formatUri = 
                (input) => input.Replace("=","==").Replace("&","&&");

            if (lister._path == null)
                return string.Format("rootUri={0}&username={1}&password={2}",
                    formatUri(lister._rootUri), lister._userName, lister._password);
            else return string.Format("host={0}&path={1}&username={2}&password={3}",
                    formatUri(lister._host), lister._path, lister._userName, lister._password);
        }
    }
}
